package com.seed.bpmn.provider.camunda.service;

import com.seed.bpmn.engine.IBPMNHistoryService;
import com.seed.bpmn.engine.common.util.Empty;
import com.seed.bpmn.engine.dto.ProcessInstanceDTO;
import com.seed.bpmn.engine.dto.TaskDTO;
import com.seed.bpmn.provider.camunda.common.util.DTOUtil;
import org.camunda.bpm.engine.HistoryService;
import org.camunda.bpm.engine.history.HistoricProcessInstance;
import org.camunda.bpm.engine.history.HistoricTaskInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>流程流转记录相关服务Camunda实现</p>
 *
 * @author cscz89@126.com
 */
@Service("bpmnHistoryService")
public class BPMNHistoryServiceImpl implements IBPMNHistoryService {

    @Autowired
    private HistoryService historyService;

    @Override
    public ProcessInstanceDTO getProcessInstance(String processInstanceId) throws Exception {
        HistoricProcessInstance p = this.historyService.createHistoricProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
        return DTOUtil.getProcessInstanceDTO(p);
    }

    @Override
    public ProcessInstanceDTO getProcessInstanceByBusinessKey(String businessKey) throws Exception {
        List<HistoricProcessInstance> list = this.historyService.createHistoricProcessInstanceQuery().processInstanceBusinessKey(businessKey).list();
        if (Empty.isNotEmpty(list)) {
            return DTOUtil.getProcessInstanceDTO(list.get(0));
        } else {
            return null;
        }
    }

    @Override
    public ProcessInstanceDTO getFinishProcessInstance(String processInstanceId) {
        HistoricProcessInstance p = this.historyService.createHistoricProcessInstanceQuery().processInstanceId(processInstanceId).finished().singleResult();
        return DTOUtil.getProcessInstanceDTO(p);
    }

    @Override
    public TaskDTO getTask(String taskId) throws Exception {
        HistoricTaskInstance t = this.historyService.createHistoricTaskInstanceQuery().taskId(taskId).singleResult();
        return DTOUtil.getTaskDTO(t);
    }

    @Override
    public List<TaskDTO> findTaskByProcessInstanceId(String processInstanceId) throws Exception {
        List<HistoricTaskInstance> tlist = this.historyService.createHistoricTaskInstanceQuery().processInstanceId(processInstanceId).list();

        List<TaskDTO> list = new ArrayList<TaskDTO>();
        for (HistoricTaskInstance t : tlist) {
            if (Empty.isNotEmpty(t)) {
                list.add(DTOUtil.getTaskDTO(t));
            }
        }
        return list;
    }
}